<?php
class UserController extends AdminController{

	public function actionIndex(){
		$mUser = new Mapper_User($this->getDb());
		$mPark = new Mapper_Park($this->getDb());
		
		$this->parks = $mPark->getAll();
		$this->users = $mUser->getAll();
		$this->options = new Set_UserOptions();
		$this->types = new Enum_UserType();
		
		$parksJson = array();
		$parksJson["null"] = "test";
		foreach($this->parks as $park){
			$parksJson[$park->park_id] = $park->park_name;
		}
		
		$this->parksJson = json_encode($parksJson);
	}

	public function actionAdd(){
		if($this->request->isPost()){
			$mUser = new Mapper_User($this->getDb());
			
			$this->unSetAll();
			$this->_view = "PureJSON";
			$this->success = false;

			if( $user = $this->request->createFromPost(new User())){
				$user->user_pass = md5($user->user_pass);
				if( $mUser->insert($user) ){
					$this->success = true;
					$this->value = $mUser->getLast();
					unset($this->value->user_pass);// = null;
				}
			}
		}
	}
	
	public function actionRemove(){
		if( $this->request->isGet() && $this->request->hasParam("user_id") ){
			$mUser = new Mapper_User($this->getDb());
			
			$this->unSetAll();
			$this->_view = "PureJSON";
			$this->success = false;
			
			if( $user = $mUser->{$this->request->getParam("user_id")} ){
				try {
					$this->success = $mUser->delete($user);
				}catch(Exception $e){
					$this->success = false;
					$this->code = $e->getMessage().".".$e->getCode();
				}
			}
		}
	}
	
	public function actionEdit(){
		if( $this->request->isAjax() ){
			$jEditable = new Mvc_Ajax_jEditable($this->request);
			$mUser = new Mapper_User($this->getDb());
			
			$this->unSetAll();
			$this->_view = "PureJSON";
			$this->success = false;
			
			$user = $mUser->{$jEditable->getId()};
			$usere = $jEditable->edit($user);
			
			if( $mUser->update($usere) ){
				$this->success = true;
				if( "park_id" == $jEditable->getCol() ){
					$this->value = $mUser->{$jEditable->getId()}->park_name;
				}else{
					$this->value = $jEditable->getValue();
				}
				
				if(null == $this->value){
					$this->value = "";
				}
			}
		}
	}
}